var util = require("../../utils/util.js")
const db = wx.cloud.database()
const eventlist = db.collection("event")
var app = getApp()
Page({
  data: {
    data1time: 10, //每次读几条
    events: [],
    readdatatime: 0, //已经读了几次  
    tabarr: ["关注", "发现", "热榜"],
    TabCur: 2,
    scrollLeft: 0,
    page: 0,
    allevents:[]
  },

  GotoSearch: function(e) {
    wx.navigateTo({
      url: '../search/search',
    })
  },

  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: '发现',
    })
    console.log(util.formatTime(new Date()))
    //发现块的记录
    //一开始先读10条记录
    var that = this
    db.collection("user").where({
      _openid: app.globalData.openID
    }).get().then(function(user) {
      that.setData({
        myclub: user.data[0].myclub
      })
      eventlist.orderBy("publishtime", "desc").get().then(
        function(res) {
          var temp = that.data.events
          var alleventstemp=that.data.allevents
          for (var i = 0; i < res.data.length; i++) {
            res.data[i].fmttimefrom = util.formatTime(res.data[i].timefrom)
            alleventstemp.push(res.data[i])
            if (user.data[0].myclub.indexOf(res.data[i].host) != -1) {
              temp.push(res.data[i])
            }
          }
          that.setData({
            events: temp,
            allevents:alleventstemp
          })
        }
      )
    })
    eventlist.limit(10).orderBy('hot', 'desc').get().then(function(res) {
      var temp2=[]
      for (var i = 0; i < res.data.length; i++) {
          res.data[i].fmttimefrom = util.formatTime(res.data[i].timefrom)
          temp2.push(res.data[i])
      }
      that.setData({
        hotevents: temp2
      })
    })

  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
  },

  GotoSeatch: function(e) {
    console.log("点击搜索框，接下来跳转到搜索页面")
  },


  Gotoeventdetail: function(event) {
    wx.navigateTo({
      url: '/pages/eventdetail/eventdetail?id=' + event.currentTarget.id,
    })
  },

  onReachBottom: function() {
    var that = this
    if (that.data.TabCur != 2) { //关注部分或发现部分
      let page = this.data.page + 20;
      eventlist.skip(page).get().then(
        function(res) {
          let new_list = []
          var alleventstemp=that.data.allevents
          for (var i = 0; i < res.data.length; i++) {
            res.data[i].fmttimefrom = util.formatTime(res.data[i].timefrom)
            alleventstemp.push(res.data[i])
            if (myclub.indexOf(res.data[i].host) != -1) {
              new_list.push(res.data[i])
            }
          }
          let old_list = that.data.events
          that.setData({
            events: old_list.concat(new_list),
            allevents:alleventstemp,
            page: page
          })
        })
    }
  }
})